import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-08-11
 * Time: 10:40
 */
public class Jdbcdemo2 {
    public static void main(String[] args) throws SQLException {//这里有可能服务器拒绝连接, 抛异常处理
        //创建数数据源, 找到数据库服务器
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java117?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("201754ljj");
        // 2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection();
        //3. 构造SQL
        String sql = "select* from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql); //发送sql语句给服务器处理
        // 4. 执行 SQL, 返回结果是一个 对象, 称为 ResultSet
        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            int id = resultSet.getInt("id"); //获取对应列的值
            String name = resultSet.getString("name");
            System.out.println(id + " " + name);
        }
        resultSet.close();
        preparedStatement.close();;
        connection.close();
    }
}
